package semantic_compute.common.yago_helper;

import common.dao.postgre.PostGreJDBCDao;
import org.slf4j.LoggerFactory;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by julianzliu on 4/22/2017.
 */
public class YagoWikipediaMap {

    static final org.slf4j.Logger logger = LoggerFactory.getLogger(YagoWikipediaMap.class);

    private PostGreJDBCDao postGreJDBCDao;
    private Connection conn;

    public YagoWikipediaMap(){
        this.postGreJDBCDao = new PostGreJDBCDao();

        this.conn = this.postGreJDBCDao.getConn();

        if(this.conn == null){
            logger.error("[ExtractorFromPostgres] Connection Failed!!!\n\n");
        }
    }


    public String mapWikipediaURLtoYagoID(String url){

        /*
        涉及到连接的时候，维基的URL有多种表示方式：
        下划线，空格，紧连
        1） ambiverse 采用 %20 转义后的空格
        2） Yago 采用下划线
         */
        String url_decode = url.replaceAll("\\%20", "_");

        String sql = String.format("select subject from yagowikipedia where predicate='<hasWikipediaUrl>' and (object='<%s>' or object='<%s>');", url , url_decode);

        logger.info("[getPartitialRowSet] sql = \n{}", sql);

        Statement stmt=null;
        ResultSet rs=null;

        String YAGO_ID = null;

        try
        {
            stmt=this.conn.createStatement();
            rs=stmt.executeQuery(sql);
            while(rs.next()){
                YAGO_ID = rs.getString("subject");
            }
            rs.close();
            stmt.close();
            //conn.close();
        }
        catch (SQLException e)
        {
            e.printStackTrace();
        }

        logger.info("[mapWikipediaURLtoYagoID] url {} map to yago {}", url, YAGO_ID);


        return YAGO_ID;
    }


    public String mapYagoIDToWikipediaURL(String yago_id){
        return null;
    }



    public static void replaceSubstringTest(){
        String a = "<http://en.wikipedia.org/wiki/Barack%20Obama>";
        String b = a.replaceAll("\\%20", "_");
        System.out.println(b);
    }


    /**************************************************
     *
     */
    public static void main(String[] args){

        replaceSubstringTest();


        YagoWikipediaMap yagoWikipediaMap = new YagoWikipediaMap();
        String YAGO_ID = yagoWikipediaMap.mapWikipediaURLtoYagoID( "http://en.wikipedia.org/wiki/Academy_Awards" );
        System.out.println("\n\nYAGO_ID OF URL IS: " + YAGO_ID + "\n\n");

    }



}
